package util
{
	public class UTF8
	{
		public function UTF8()
		{
		}
		
		/**解碼*/
		public static function decode(arr:Array):String
		{
			var index:int = 0;
			var str:String ="";
			while(index < arr.length){
				var count:int = bytesCount(arr[index]);
				var tmpArr:Array = [];
				for(var i:int = 0; i < count; i++){
					tmpArr.push(arr[index + i]);
				}
				if(tmpArr.length > 0){
					str += utf8Value(tmpArr);
				}
				index += count;
			}
			return str;
		}
		
		private static function bytesCount(byte:int):int
		{
			var n:int = 1;
			if((byte & 0x80) == 0x80){
				if((byte & 0xC0)  == 0xC0){
					n = 2;
					if((byte & 0xE0) == 0xE0){
						n=3;
						if((byte &  0xF0) == 0xF0){
							n = 4;
						}
					}
				}
			}
			return n;
		}
		
		private static function utf8Value(arr:Array):String
		{
			var ret:int = 0;
			switch(arr.length){
				case 1:
					ret = arr[0];
					break;
				case 2:
					ret = ((arr[0] & 0x1F) << 6) + (arr[1] & 0x3F); 
					break;
				case 3:
					ret = ((arr[0] & 0xF) << 12) + ((arr[1] & 0x3F) << 6) + (arr[2] & 0x3F); 
					break;
				case 4:
					ret = ((arr[0] & 0x7) << 18) + ((arr[1] & 0x3F) << 12) + ((arr[2] & 0x3F)) << 6 + (arr[1] & 0x3F); 
					break;
			}
			return String.fromCharCode(ret);
		}
	}
}